// 封装axios
import store from '@/store'
import { Logout, saveToken } from '@/store/actions/login'
import axios, { AxiosError } from 'axios'
import { getToken } from './storage'
import  history from './history'
import { Toast } from 'antd-mobile'
// const baseURL = 'http://geek.itheima.net/v1_0/'
const baseURL = 'http://toutiao.itheima.net/v1_0/'
const instance = axios.create({
  baseURL,
  timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    const token = getToken().token
    if(token){
      config.headers!.Authorization=`Bearer ${token}`
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response
  },
  async function (error) {
    // 对响应错误做点什么
    console.dir(error,'6666');
    const err = error as AxiosError
    if (!error.response) {
      Toast.show('网络异常')
      return Promise.reject(error)
    }
    if (error.response.status !== 401) {
      Toast.show('后端错误')
      return Promise.reject(error)
    }
    const refresh_token= getToken().refresh_token
         //当返回是401时
      if(!refresh_token){
        history.replace('/login', { from: history.location.pathname })
        Toast.show('登录信息过期')
        return Promise.reject(error)
      }
      try{
        //当有这个token时
         const res = await axios.put(baseURL+'authorizations',null,{ //重新发请求
            headers:{
              Authorization: `Bearer ${refresh_token}`
            }
          })
          const NewToken = {token:res.data.data.token,refresh_token}
        //  store.dispatch({type:'login/token',payload:NewToken}) //储存新token到redux
        store.dispatch(saveToken(NewToken))
         return instance(err.config) //重新发送请求
      }catch(e){
        store.dispatch(Logout())
        history.replace('/login', { from: history.location.pathname })
        return Promise.reject(error)
      }
  }
)

export default instance
